package com.yy.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageInfo;
import com.yy.domain.GptCtDO;
import com.yy.domain.GptDoctorEvaluationDO;
import com.yy.dao.GptDoctorEvaluationMapper;
import com.yy.domain.GptDoctorValueEvaluationDO;
import com.yy.domain.LoginUser;
import com.yy.dto.GptDoctorEvaluationDTO;
import com.yy.service.GptCtService;
import com.yy.service.GptDoctorEvaluationService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yy.service.GptDoctorValueEvaluationService;
import com.yy.service.UserContextService;
import com.yy.utils.ConvertUtils;
import com.yy.vo.DoctorPageVO;
import com.yy.vo.EvaluationVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 姚欣宏
 * @since 2023-11-09
 */
@Service
public class GptDoctorEvaluationServiceImpl extends ServiceImpl<GptDoctorEvaluationMapper, GptDoctorEvaluationDO> implements GptDoctorEvaluationService {

    @Autowired
    GptDoctorValueEvaluationService gptDoctorValueEvaluationService;

    @Autowired
    GptCtService gptCtService;

    @Autowired
    private UserContextService userContextService;

    @Override
    public PageInfo<GptDoctorEvaluationDTO> getGptDoctors(DoctorPageVO doctorPageVO) {
        //获取分页参数
        int pageSize = doctorPageVO.getPageSize();
        int pageNum = doctorPageVO.getPageNum();
        //评价状态：0表示待评价，1表示医生已评价
        Integer evaluationStatus = doctorPageVO.getEvaluationStatus();
        // 使用UserContextService来获取当前用户信息
        LoginUser currentUser = userContextService.getCurrentUser();
        Long userId = currentUser.getUser().getId(); // 使用方法获取用户ID
        //查询原始数据
        List<GptDoctorEvaluationDTO> gptDoctorEvaluationDTOList = this.baseMapper.selectDoctorEvaluations();
        QueryWrapper<GptDoctorEvaluationDO> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        List<GptDoctorEvaluationDO> gptDoctorEvaluationDOS = list(wrapper);
        if (CollUtil.isEmpty(gptDoctorEvaluationDOS)) {
            gptDoctorEvaluationDTOList.forEach(dto -> dto.setEvaluationStatus(0)); // 设置状态为“待评价”
        } else {
            // 将DTO和DO的列表关联起来，并更新状态和创建日期
            Map<Integer, GptDoctorEvaluationDO> doMap = gptDoctorEvaluationDOS.stream()
                    .collect(Collectors.toMap(GptDoctorEvaluationDO::getGptCtId, Function.identity()));
            gptDoctorEvaluationDTOList.forEach(dto -> {
                GptDoctorEvaluationDO matchedDO = doMap.get(dto.getId().intValue());
                if (matchedDO != null) {
                    dto.setEvaluationStatus(matchedDO.getEvaluationStatus());
                    dto.setCreateDate(matchedDO.getCreateDate());
                } else {
                    dto.setEvaluationStatus(0); // 设置状态为“待评价”
                }
            });
        }
        if (evaluationStatus != null) {
            gptDoctorEvaluationDTOList = gptDoctorEvaluationDTOList.stream()
                    .filter(dto -> evaluationStatus.equals(dto.getEvaluationStatus()))
                    .collect(Collectors.toList());
        }
        gptDoctorEvaluationDTOList.forEach(dto -> {
            String desValue = dto.getDesValue();
            String extractedText = extractDesiredText(desValue);
            dto.setDesValue(extractedText);
        });
        // 计算总数用于分页信息，因为已经进行过过滤
        int total = gptDoctorEvaluationDTOList.size();
        // 计算当前页应有的数据条目的起始索引和结束索引
        int fromIndex = (pageNum - 1) * pageSize;
        int toIndex = Math.min(fromIndex + pageSize, total);
        // 根据分页参数获取子列表
        List<GptDoctorEvaluationDTO> pageData = gptDoctorEvaluationDTOList.subList(fromIndex, toIndex);
        // 创建PageInfo对象，并设置相关分页信息
        PageInfo<GptDoctorEvaluationDTO> pageInfo = new PageInfo<>(pageData);
        pageInfo.setTotal(total);
        pageInfo.setPageSize(pageSize);
        pageInfo.setPageNum(pageNum);
        pageInfo.setPages((total + pageSize - 1) / pageSize); // 计算总页数
        //返回分页信息
        return pageInfo;
    }
    private String extractDesiredText(String originalText) {
        // 此正则表达式将匹配“检查技术：”后面的任意文本，直到“影像诊断：”或“影像所见：”为止
        String patternString = "检查技术：\\s*(.*?)(\\s*影像诊断：|\\s*影像所见：)";
        Pattern pattern = Pattern.compile(patternString, Pattern.DOTALL);
        Matcher matcher = pattern.matcher(originalText);
        if (matcher.find()) {
            return matcher.group(1);
        }
        return originalText; // 如果没有匹配到，则返回原始文本
    }

    @Override
    public GptDoctorEvaluationDTO getGptDoctor(Integer id) {
        // 使用UserContextService来获取当前用户信息
        LoginUser currentUser = userContextService.getCurrentUser();
        Long userId = currentUser.getUser().getId(); // 使用方法获取用户ID
        GptCtDO gptCtDO = gptCtService.getById(id);
        Integer gptId = gptCtDO.getId();
        QueryWrapper<GptDoctorEvaluationDO> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        wrapper.eq("gpt_ct_id", gptId);
        GptDoctorEvaluationDO gptDoctorEvaluationDO = getOne(wrapper);
        if (ObjectUtil.isNull(gptDoctorEvaluationDO)) {
            gptDoctorEvaluationDO = new GptDoctorEvaluationDO();
            gptDoctorEvaluationDO.setGptCtId(gptId);
            gptDoctorEvaluationDO.setUserId(Math.toIntExact(userId));
            gptDoctorEvaluationDO.setCreateDate(new Date());
            gptDoctorEvaluationDO.setEvaluationStatus(0);
            save(gptDoctorEvaluationDO);
        }
        GptDoctorEvaluationDTO gptDoctorEvaluationDTO = new GptDoctorEvaluationDTO();
        gptDoctorEvaluationDTO.setDesValue(gptCtDO.getSrcValue());
        gptDoctorEvaluationDTO.setGptValue2(gptCtDO.getGptValue2());
        gptDoctorEvaluationDTO.setEvaluationStatus(gptDoctorEvaluationDO.getEvaluationStatus());
        gptDoctorEvaluationDTO.setGptValue2Id(gptDoctorEvaluationDO.getGptValue2Id());
        gptDoctorEvaluationDTO.setId(Long.valueOf(gptDoctorEvaluationDO.getId()));
        return gptDoctorEvaluationDTO;
    }

    @Override
    public Integer insertEvaluate(EvaluationVO evaluationVO) {
        GptDoctorValueEvaluationDO gptDoctorValueEvaluationDO = ConvertUtils.beanCopy(evaluationVO, GptDoctorValueEvaluationDO.class);
        gptDoctorValueEvaluationDO.setCreateDate(new Date());
        if (ObjectUtil.isNotNull(evaluationVO.getId())) {
            gptDoctorValueEvaluationService.updateById(gptDoctorValueEvaluationDO);
        } else {
            gptDoctorValueEvaluationService.save(gptDoctorValueEvaluationDO);
        }
        Integer id = gptDoctorValueEvaluationDO.getId();
        Integer gptSort = evaluationVO.getGptSort();
        Integer gptCtId = evaluationVO.getGptCtId();
        LoginUser currentUser = userContextService.getCurrentUser();
        Long userId = currentUser.getUser().getId(); // 使用方法获取用户ID
        QueryWrapper<GptDoctorEvaluationDO> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        wrapper.eq("gpt_ct_id", gptCtId);
        GptDoctorEvaluationDO gptDoctorEvaluationDO = getOne(wrapper);
        if (gptSort == 0) {
            gptDoctorEvaluationDO.setGptValueId(id);
        } else if (gptSort == 1) {
            gptDoctorEvaluationDO.setGptValue1Id(id);
        } else if (gptSort == 2) {
            gptDoctorEvaluationDO.setGptValue2Id(id);
        }
        gptDoctorEvaluationDO.setEvaluationStatus(1);
        updateById(gptDoctorEvaluationDO);
        return gptDoctorEvaluationDO.getId();
    }

    @Override
    public GptDoctorValueEvaluationDO getGptDoctorOne(Integer gptSort, Integer gptCtId) {
        LoginUser currentUser = userContextService.getCurrentUser();
        Long userId = currentUser.getUser().getId(); // 使用方法获取用户ID
        QueryWrapper<GptDoctorEvaluationDO> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        wrapper.eq("gpt_ct_id", gptCtId);
        GptDoctorEvaluationDO gptDoctorEvaluationDO = getOne(wrapper);
        Integer gptValueId = null;
        if (gptSort == 0) {
            gptValueId = gptDoctorEvaluationDO.getGptValueId();
        } else if (gptSort == 1) {
            gptValueId = gptDoctorEvaluationDO.getGptValue1Id();
        } else if (gptSort == 2) {
            gptValueId = gptDoctorEvaluationDO.getGptValue2Id();
        }
        if (ObjectUtil.isNotNull(gptValueId)) {
            return gptDoctorValueEvaluationService.getById(gptValueId);
        }
        return null;
    }

    @Override
    public GptDoctorEvaluationDTO updateOne(Integer id) {
        GptDoctorEvaluationDO gptDoctorEvaluationDO = getById(id);
        gptDoctorEvaluationDO.setEvaluationStatus(1);
        updateById(gptDoctorEvaluationDO);
        return null;
    }

}
